from rest_framework import serializers
from django.contrib.auth import authenticate
from rest_framework_jwt.utils import jwt_payload_handler,jwt_encode_handler
from django.conf import settings
import json
import hmac
import base64


# def CreateJWTtoken(user):
#     header_data = {'typ': 'JWT', 'alg': 'HS256'}
#     header = base64.b64encode(json.dumps(header_data).encode())
#     payload_data = {"username":user.username,"password":user.password}
#     payload = base64.b64encode(json.dumps(payload_data).encode())
#     data = header + b"." + payload
#     signature = hmac.new(settings.SECRET_KEY,data,digestmod="sha3_256").hexdigest()
#     token = data.decode() + "." + signature
#     return token

class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=150,label="用户名")
    password = serializers.CharField(max_length=128,label="密码")

    def validate(self, attrs):
        username = attrs["username"]
        password = attrs["password"]
        user = authenticate(username=username,password=password)
        if not user:
            raise serializers.ValidationError("用户名、密码不匹配")
        if not user.is_staff:
            raise serializers.ValidationError("无权限")

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return {
            "user_id":user.id,
            "username":username,
            "token":token,
        }
